<template>
    <a-modal v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false"
        :width="width >= 600 ? 600 : '100%'" draggable @before-ok="save" @close="reset">
        <GiForm ref="formRef" v-model="form" :columns="columns" />
    </a-modal>
</template>

<script setup lang="ts">
    import { Message } from '@arco-design/web-vue'
    import { useWindowSize } from '@vueuse/core'
    import { getConsumableTracks, addConsumableTracks, updateConsumableTracks } from '@/apis/asset/consumable/tracks'

    import { consumableUsage } from '@/apis/asset/consumable/records'

    import { type ColumnItem, GiForm } from '@/components/GiForm'
    import { useResetReactive } from '@/hooks'
    import { useDict } from '@/hooks/app'
    import { consumables } from '@/hooks/asset'

    import { listUserDict } from '@/apis'
    import { useDept } from '@/hooks/app'

    const emit = defineEmits < {
    (e: 'save-success'): void
  }> ()

    const { width } = useWindowSize()
    const visible = ref(false)

    const title = computed(() => ('耗材领用'))
    const formRef = ref < InstanceType < typeof GiForm >> ()

    const { consumableList, getConsumableList } = consumables()

    const { deptList, getDeptList } = useDept()

    const userList = ref < LabelValueState[] > ([]);
    // 获取用户数据
    const onSelect = async (deptId) => {
        const queryData = { status: 1, deptId: deptId }
        const { data } = await listUserDict(queryData)
        userList.value = data.map((item) => ({ ...item, value: `${item.value}` }))
    }

    const [form, resetForm] = useResetReactive({
        // todo 待补充
    })

    const columns: ColumnItem[] = reactive([
        {
            label: '耗材',
            field: 'consumableId',
            type: 'select',
            span: 24,
            required: true,
            props: {
                options: consumableList,
                placeholder: "请选择耗材",
                allowClear: true,
                allowSearch: true,
            }
        },

        {
            label: '领用数量',
            field: 'changeNum',
            type: 'input-number',
            span: 24,
            rules: [{ required: true, message: '请输入领用数量' }]
        },

        {
            label: '领用部门',
            field: 'usageDeptId',
            type: 'tree-select',
            span: 24,
            required: true,
            props: {
                data: deptList,
                allowClear: true,
                allowSearch: true,
                fallbackOption: false,
                filterTreeNode(searchKey: string, nodeData: TreeNodeData) {
                    if (nodeData.title) {
                        return nodeData.title.toLowerCase().includes(searchKey.toLowerCase())
                    }
                    return false
                },
                onChange(value) {
                    onSelect(value)
                },
            },
        },
        {
            label: '领用人',
            field: 'usageUserId',
            type: 'select',
            span: 24,
            required: true,
            props: {
                options: userList,
                placeholder: "请选择用户",
                allowClear: true,
                allowSearch: true,
                allowCreate: true,
            },
        },

        {
            label: '描述',
            field: 'description',
            type: 'textarea',
            props: {
                maxLength: 250
            },
            span: 24,
        },

    ])

    // 重置
    const reset = () => {
        formRef.value?.formRef?.resetFields()
        resetForm()
    }

    // 保存
    const save = async () => {
        try {
            const isInvalid = await formRef.value?.formRef?.validate()

            const data = await consumableUsage(form)
            if (data.data.id < 0)
                Message.error('库存数量不足')
            else
                Message.success('领用成功')
            emit('save-success')
            return true
        } catch (error) {
            return false
        }
    }

    // 领用
    const onOpen = async () => {
        reset()
        visible.value = true
        if (!consumableList.value.length) {
            await getConsumableList()
        }
        if (!deptList.value.length) {
            await getDeptList()
        }
    }

    defineExpose({ onOpen })
</script>

<style scoped lang="scss"></style>